package cn.hdu.community.service.serviceImpl;

import cn.hdu.community.dto.Result;
import cn.hdu.community.entity.User;
import cn.hdu.community.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @Author zhangxin
 * @Date 2022/4/10
 */
@Service
public class FileServiceImpl implements FileService {
    @Value("${spring.servlet.multipart.max-file-size}")
    private String FILE_MAX_SIZE;

    @Override
    public Result uploadImgFile(MultipartFile uploadFile) {
        // 1. 获取要上传文件的文件名
        String fileName = uploadFile.getOriginalFilename();
        // 2. 自定义上传路径
        String path = System.getProperty("user.dir") + "\\src\\main\\resources\\upload";
        // 3. 判断路径是否存在，不存在则新建
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        // 3.改名,避免重名,定义新文件的名字
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar calendar = Calendar.getInstance();
        String time = sFormat.format(calendar.getTime());
        assert fileName != null;
        String newName = path + File.separator + time + fileName.substring(fileName.lastIndexOf("."));
        try {
            uploadFile.transferTo(new File(newName));
            return Result.success("上传成功", newName);
        } catch (IOException e) {
            return Result.internalError(null);
        }
    }

    @Override
    public Result checkImgFileSiz(MultipartFile uploadFile) {
        double uploadFileSize = uploadFile.getSize() / 1024.0 / 1024.0;
        if (uploadFileSize > Double.parseDouble(FILE_MAX_SIZE.substring(0, 2))) {
            return Result.error("文件超过" + FILE_MAX_SIZE + "，请重新选择", null);
        } else {
            return Result.success("检验通过", null);
        }
    }
}
